\documentclass[letterpaper]{article}
\topmargin = -.25in
\oddsidemargin = -.25in
\evensidemargin = -.25in
\headheight = .65in
\headsep = .05in
\textheight = 9.3in
\textwidth = 7in
\usepackage[includehead,centering,hscale=0.85,vscale=0.95]{geometry}
\usepackage{amsmath}
\usepackage{verbatim}
\newenvironment{code}{\footnotesize\verbatim}{\endverbatim\normalsize}
\begin{document}
\section{Game Protocol}
   \subsection{Client Orders Message}
      \begin{tabular}{l|l|l|l|l|l|l}
      Entity&  Action&  Args\\
      \hline
      player&  auction& TradeGoodGPT&  GPT&           TTL&        StartBid&   Blacklist\\
      player&  auction& TradeGoodType& TradeGoodId&   StartBid&   Blacklist&  \\
      player&  bid&     AuctionId&     MaxBid&        &           &\\
      player&  tribute& TradeGoodId&   PlayerId&      &           &\\
      player&  build&   UnitType&      &              &           &\\
      unit&    move&    UnitId&        Loc (empty)&   &           &\\
      unit&    attack&  UnitId&        Loc (w/Ship)&  WeaponId&   &\\
      unit&    board&   UnitId&        Loc (w/Ship)&  &           &\\
      unit&    mine&    UnitId&        Loc (w/Asteroid)& &        &\\
      \end{tabular}
      \begin{verbatim}
      PlayerId = String
      UnitId = StockId = TradeGoodId = WeaponId = Integer
      TradeGoodType = Unit | Stock | Contract | GoldPerTurn
      Blacklist = [PlayerId]
      StartBid = MaxBid = GoldAmt = GPT = Integer
      TTL = Integer
      Loc = (Integer,Integer)
      UnitType = [Integer]
      \end{verbatim}
   \subsection{Server State Message}
      \begin{itemize}
      \item State: Properties (id, team, loc, health, value, upgrades) of objects you can see (Asteroids, Ships, Loot) in range of your ships' sensors.
      \item Events: Orders successfully committed by units you can see.
      \item Trade: Auctions, bids, and tributes that you are allowed to know about.
      \item Messages: Invalid orders, Trash Talk, Narration?
      \end{itemize}
\section{XML Schema}
   Haskell server order construction, followed by equivalent xml
   \subsection{Client $\rightarrow$ Server}
      \begin{verbatim}
      BuildOrder   [1,0,5,0,23]
      <player action="build" unitType="[1,0,5,0,23]" />
      AuctionOrder (TradeContract 3) 1000 []
      <player action="auction" tgType="contract" tgid="3" amt="1000" blacklist="[]" />
      AuctionOrder (TradeGPT 15 100) 1000 []
      <player action="auction" tgType="GPT" gpt="15" ttl="100" amt="1000" blacklist="[]" />
      AuctionOrder (TradeUnit 12) 1000 []
      <player action="auction" tgType="unit" tgid="12" amt="1000" blacklist="[]" />
      AuctionOrder (TradeStock 1) 1000 []
      <player action="auction" tgType="stock" tgid="1" amt="1000" blacklist="[]" />
      BidOrder     12 1500
      <player action="bid" aid="12" bid="1500" />
      TributeOrder (TradeUnit 3) (B.pack "bob")
      <player action="tribute" tgType="unit" tgid="3" pid="bob" />
      MineOrder    2 (58,90)
      <unit id="2" action="mine" loc="(58,90)" />
      MoveOrder    1 (58,92)
      <unit id="1" action="move" loc="(58,92)" />
      AttackOrder  0 (56,-128) 0
      <unit id="0" action="attack" wid="0" loc="(56,-128)" />
      AttackOrder  0 (56,-128) 1
      <unit id="0" action="attack" wid="1" loc="(56,-128)" />
      AttackOrder  0 (56,-128) 2
      <unit id="0" action="attack" wid="2" loc="(56,-128)" />
      \end{verbatim}
   \subsection{Server $\rightarrow$ Client}
      Unimplmented

\section{Coding Guidelines}
Document code with tags such as\\
NOTE: important remark or reminder for future work\\
TODO: must be implemented but hasn't (or not fully) been yet\\
FIXME: should be changed or fixed (bugs, refactoring/cleanup)\\
QUESTION: decisions posed to other developers\\
IMPROVE: possible improvements (eg performance, features) that probably aren't critical

\section{Server Architecture}
The server is split into 5 major subcomponents.
Of these, daemons (noted by a 'd' suffix) each exist in their own thread.
Each daemon is a singleton with an exception of $clientd$, of which there is an instance for each player, and so the system uses $3+N$ threads for $N$ players.
Concurrency issues are resolved by a mixture of message passing between major components via "mailboxes", effectively a queued message channel ontop of software transactional memory (via $TChan$s) and by software transactional memory proper.

$acceptd$ listens for, accepts, and validates prospective clients who wish to connect to the server.
Upon validation it creates or locates client data channels ($mbox$) and passes handling of the client to the $clientd$ swarm.

$clientd$ listens on a socket handle for order strings sent by the client, which if found are placed into the $OrderBox$ and tagged with the client's username.
Additionally, it also will check the client's mailbox for state updates from the server, which it will imediately forward to the client when available.

$procd$ aggregates client orders and when each player has readied orders, executes a game tick and updates state.

$xmld$ parses xml order strings into actual player order structures, which are made available for $procd$.

$game$ calculates the new game state for each turn based on the previous turn's state and the player orders.  All of $game$ is pure code.

This design was chosen as it allows good pipelining of the most expensive components (IO and parsing) while still retaining simplicity and clarity.
Additionally, it can be easily extended to have additional threads handling parsing or game logic calculation if needed.

\section{Networking}
   \subsection{Overview}
      \begin{itemize}
      \item Use incomming and outgoing "mailboxes" to queue messages and allow for disconnect/resume.
      \item Create mbox for visualizer upon init, to allow connecting a viz at any point.
            The viz data is personalized for the player specified by command line option (in accordance for fog of war).
      \item Once server has orders for all players, we process a turn.
      \end{itemize}
   \subsection{(Re)Connect}
      \begin{enumerate}
      \item Client: Send username; send password.
      \item Server: Validate (fail=send warning and disconnect,pass=no-op) or create client and initialize inbox.
      \end{enumerate}
   \subsection{While Connected}
      Server send any state messages queued in client's inbox, and processes any order strings that are waiting on socket handle.
      Any additional order string beyond the first for some turn will replace the previous one (until calculation begins).
   \subsection{Psudeo Example}
      \begin{enumerate}
      \item Client: Send username; send password.
      \item Server: Send validation success; send gamestate.
      \item Client: Send orders list.
      \item Server: Send game state.
      \item \dots etc \dots
      \end{enumerate}
      The flow can restart at \#1 at any point without problems.  Note, if the client missed a turn (likely if disconnected), they obviously must send orders for the current turn- which may require allowing the server to send numerous gamestates in a row before they take action.

\end{document}
